import { defineStore } from 'pinia'
import { ref } from 'vue'
import service from '../utils/request'
import { ElMessage } from 'element-plus'
import { el } from 'element-plus/es/locales.mjs'

export const useRoomStore = defineStore('room', () => {
  const rooms = ref([])

  const fetchRooms = async () => {
    try {
      const response = await service.get('/staff/rooms')
      if (response.data.code === 200 && response.data.data) {
        // 转换状态为中文
        rooms.value = response.data.data.map(room => ({
          ...room,
          status: room.status === 'idle' ? '空闲' : 
                  room.status === 'in_used' ? '使用中' : 
                  room.status === 'maintenance' ? '维护中' : 
                  room.status === 'locked' ? '锁定中' : room.status
        }))
      } else {
        ElMessage.error(response.data.message || '获取会议室数据失败')
      }
    } catch (error) {
      console.error('获取会议室数据失败:', error)
      ElMessage.error('获取会议室数据失败')
    }
  }

  const updateRoomStatus = async (roomId, status) => {
    try {
      const englishStatus = convertStatusToEnglish(status)
      const response = await service.put('/staff/rooms', {
        id: roomId,
        status: englishStatus
      })

      if (response.data.code === 200) {
        const roomIndex = rooms.value.findIndex(r => r.id === roomId)
        if (roomIndex !== -1) {
          rooms.value[roomIndex].status = status
          rooms.value[roomIndex].startHour = null
          rooms.value[roomIndex].endHour = null
        }
        return true
      } else {
        ElMessage.error(response.data.message || '状态修改失败')
        return false
      }
    } catch (error) {
      console.error('状态修改失败:', error)
      ElMessage.error('状态修改失败')
      return false
    }
  }

  const convertStatusToEnglish = (status) => {
    switch (status) {
      case '空闲':
        return 'idle'
      case '维护中':
        return 'maintenance'
      case '使用中':
        return 'in_used'
      case '锁定中':
        return 'locked'
      default:
        return status
    }
  }

  const getAllRoomsName = async () => {
    const roomNames = await service.get('/staff/rooms/name')
    console.log(roomNames)
    if (roomNames.data.code === 200 && roomNames.data.data) {
      return roomNames.data.data
    }else{
      ElMessage.error(roomNames.data.message || '获取会议室名称失败')
    }
  }

  return {
    rooms,
    fetchRooms,
    updateRoomStatus,
    getAllRoomsName
  }
})